package com.smartinput.sync.controller

import com.mensanyun.kotool.util.executeWithTry
import com.smartinput.sync.application.dto.*
import com.smartinput.sync.application.service.TextSyncService
import jakarta.validation.Valid
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/api/sync")
class SyncController(
    private val textSyncService: TextSyncService
) {

    @PostMapping("/push/device")
    fun pushTextToDevice(@Valid @RequestBody request: TextPushRequest): ResponseEntity<TextPushResponse> {
        val principal = org.springframework.security.core.context.SecurityContextHolder.getContext().authentication.principal
        val currentUserId = if (principal is org.springframework.security.core.userdetails.UserDetails) {
            principal.username
        } else {
            principal.toString()
        }
        
        val success = textSyncService.pushTextToDevice(
            sourceUserId = currentUserId,
            sourceDeviceId = request.sourceDeviceId,
            targetDeviceId = request.targetDeviceId,
            content = request.content
        )
        
        return ResponseEntity.ok(TextPushResponse(success = success))
    }
    
    @PostMapping("/push/all")
    fun pushTextToAllDevices(@Valid @RequestBody request: TextPushAllRequest): ResponseEntity<TextPushAllResponse> {
        val principal = org.springframework.security.core.context.SecurityContextHolder.getContext().authentication.principal
        val currentUserId = if (principal is org.springframework.security.core.userdetails.UserDetails) {
            principal.username
        } else {
            principal.toString()
        }
        
        val results = textSyncService.pushTextToAllUserDevices(
            userId = currentUserId,
            sourceDeviceId = request.sourceDeviceId,
            content = request.content
        )
        
        return ResponseEntity.ok(TextPushAllResponse(results = results))
    }

    @PostMapping("/notify")
    fun notifyTextReceived(@Valid @RequestBody request: TextReceivedNotification) = executeWithTry {
        textSyncService.notifyTextReceived(
            targetDeviceId = request.targetDeviceId,
            content = request.content,
            sourceDeviceId = request.sourceDeviceId
        )
    }
} 